package com.atguigu.edu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.edu.util.ClickHouseUtil;
import com.atguigu.edu.util.DateFormatUtil;
import com.atguigu.edu.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsUserPageViewWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1 获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //设置并行度
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 2 设置检查点和状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        //TODO 3 读取kafka中页面数据
        String topicName = "dwd_traffic_page_log";
        String groupId = "dws_user_page_view_window";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));

        //TODO 4 过滤出首页和商品详情页数据
        SingleOutputStreamOperator<JSONObject> jsonObjStream =
                streamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
                    @Override
                    public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(value);
                        JSONObject page = jsonObject.getJSONObject("page");
                        if ("home".equals(page.getString("page_id")) || "course_detail".equals(page.getString(
                                "page_id"))) {
                            out.collect(jsonObject);
                        }

                    }
                });

        //TODO 5 设置水位线
        SingleOutputStreamOperator<JSONObject> beanWithWatermarkStream =
                jsonObjStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("ts");
                    }
                }));

        //TODO 6 根据mid分组 并去重
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = beanWithWatermarkStream.keyBy(s -> s.getJSONObject("common").getString("mid"))
                .flatMap(new RichFlatMapFunction<JSONObject, TrafficHomeDetailPageViewBean>() {
                    ValueState<String> homeLastVisitDtState = null;
                    ValueState<String> detailLastVisitDtState = null;

                    @Override
                    public void open(Configuration parameters) throws Exception {

                        ValueStateDescriptor<String> homeLastVisitDt = new ValueStateDescriptor<>(
                                "home_last_visit_dt", String.class);
                        homeLastVisitDt.enableTimeToLive(StateTtlConfig
                                .newBuilder(org.apache.flink.api.common.time.Time.days(1L))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build());
                        homeLastVisitDtState = getRuntimeContext().<String>getState(homeLastVisitDt);
                        ValueStateDescriptor<String> detailLastVisitDt = new ValueStateDescriptor<>(
                                "detail_last_visit_dt",
                                String.class);
                        detailLastVisitDt.enableTimeToLive(StateTtlConfig
                                .newBuilder(org.apache.flink.api.common.time.Time.days(1L))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build());

                        detailLastVisitDtState = getRuntimeContext().getState(detailLastVisitDt);
                    }

                    @Override
                    public void flatMap(JSONObject value, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        // 判断数据为首页还是详情页
                        String pageId = value.getJSONObject("page").getString("page_id");
                        String visitDt = DateFormatUtil.toDate(value.getLong("ts"));
                        if ("home".equals(pageId)) {
                            String homeLastVisit = homeLastVisitDtState.value();
                            if (homeLastVisit == null || !homeLastVisit.equals(visitDt)) {
                                homeLastVisitDtState.update(visitDt);
                                out.collect(new TrafficHomeDetailPageViewBean("", "", 1L, 0L, value.getLong("ts")));
                            }
                        } else {
                            String detailLastVisit = detailLastVisitDtState.value();
                            if (detailLastVisit == null || visitDt.equals(detailLastVisit)) {
                                detailLastVisitDtState.update(detailLastVisit);
                                out.collect(new TrafficHomeDetailPageViewBean("", "", 0L, 1L, value.getLong("ts")));
                            }
                        }


                    }
                });

        //TODO 7 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream =
                beanStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1,
                                                                TrafficHomeDetailPageViewBean value2) throws Exception {
                        value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                        value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                        return value1;
                    }
                }, new AllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TrafficHomeDetailPageViewBean> values,
                                      Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TrafficHomeDetailPageViewBean trafficHomeDetailPageViewBean = values.iterator().next();
                        trafficHomeDetailPageViewBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        trafficHomeDetailPageViewBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        trafficHomeDetailPageViewBean.setTs(System.currentTimeMillis());
                        out.collect(trafficHomeDetailPageViewBean);
                    }
                });

        //TODO 8 写出到clickHouse中
        resultStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_user_page_view_window values(?,?,?,?,?)"));

        // TODO   执行任务
        env.execute();
    }
}
